package com.asia5b.a5mall.goods.activity

import androidx.recyclerview.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5mall.goods.R
import com.asia5b.a5mall.goods.adapter.SearchKeyHistoryAdapter
import com.asia5b.a5mall.goods.adapter.SearchKeyHotAdapter
import com.asia5b.a5mall.goods.adapter.SearchServiceKeyAdapter
import com.asia5b.a5mall.goods.databinding.ActivitySearchkeyBinding
import com.asia5b.a5mall.middleware.base.SimpleActivity
import com.asia5b.a5mall.middleware.logic.viewmodel.goods.SearchKeyActivityVM
import com.asia5b.a5mall.middleware.model.bean.HistoryBean
import com.asia5b.a5mall.middleware.model.goods.HotModel
import com.asia5b.a5mall.middleware.model.goods.KeywordModel
import com.asia5b.a5mall.middleware.utils.*
import com.asia5b.a5mall.middleware.widget.BaseTextWatcher
import com.asia5b.a5mall.middleware.widget.CancelSureViewModel
import com.google.android.flexbox.FlexboxLayoutManager
import com.jakewharton.rxbinding3.widget.textChanges
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_searchkey.*
import java.util.concurrent.TimeUnit

/**
 * Created by zhangyuncai on 2020/1/11.
 * 搜索关键词展示列表
 */
@Route(path = ActCons.SearchKeyActivity)
class SearchKeyActivity : SimpleActivity<SearchKeyActivityVM, ActivitySearchkeyBinding>() {
    override val viewModelClazz: Class<SearchKeyActivityVM>
        get() = SearchKeyActivityVM::class.java

    override fun getDataBinding(): ActivitySearchkeyBinding {
        return ActivitySearchkeyBinding.inflate(layoutInflater)
    }

    override var sIsDark = true

    val hotDatas = arrayListOf<HotModel>()
    val hotAdapter by lazy { SearchKeyHotAdapter(hotDatas) }
    val hotRecyclerView by lazy { rv_search_hot }

    val serviceKeyDatas = arrayListOf<KeywordModel>()
    val serviceKeyAdapter by lazy { SearchServiceKeyAdapter(serviceKeyDatas) }
    val serviceKeyRecyclerView by lazy { rv_search_servicekey }

    val historyDatas = arrayListOf<HistoryBean>()
    val historyAdapter by lazy { SearchKeyHistoryAdapter(historyDatas) }
    val historyRecyclerView by lazy { rv_search_history }

    val etSearch by lazy { et_search_key }
    val tvShop by lazy { tv_search_shop }
    val llShop by lazy { ll_search_shop_vessel }

    override fun initView() {
        hotRecyclerView.run {
            layoutManager = FlexboxLayoutManager(mActivity)!!
            adapter = hotAdapter
        }
        historyRecyclerView.run {
            layoutManager = LinearLayoutManager(mActivity)!!
            adapter = historyAdapter
            addItemDecoration(newDivider(mActivity))
        }
        serviceKeyRecyclerView.run {
            layoutManager = LinearLayoutManager(mActivity)!!
            adapter = serviceKeyAdapter
            addItemDecoration(newDivider(mActivity))
        }

        mViewModel.loadHotDatas()
        mViewModel.loadHistoryDatas()

    }

    /**
     * 显示店铺搜索字样
     */
    fun notifyShopView(text: String) {

        if (text.count() > 0) {
            ll_searchkey_servicekey.visibility = View.VISIBLE
            tvShop.text = getString(R.string.搜索_数_店铺, "${etSearch.text}")
        } else {
            tvShop.text = ""
            ll_searchkey_servicekey.visibility = View.GONE
            serviceKeyDatas.clear()
            serviceKeyAdapter.notifyDataSetChanged()
        }
    }

    fun notifyHotView() {
        hotAdapter.notifyDataSetChanged()
    }

    fun notifyHistoryView() {
        bt_search_clear.visibility = (historyDatas.size == 0).judge(View.GONE, View.VISIBLE)
        ll_search_history.visibility = (historyDatas.size == 0).judge(View.GONE, View.VISIBLE)
        historyAdapter.notifyDataSetChanged()
    }

    override fun initEvent() {
        tv_search_back.setOnClickListener {
            pop()
        }
        etSearch.addTextChangedListener(object : BaseTextWatcher() {
            override fun onTextChanged(charSequence: CharSequence?, start: Int, count: Int, after: Int) {
                notifyShopView(etSearch.text.toString())
            }
        })
        etSearch.setOnEditorActionListener { v, actionId, event ->
            if (etSearch.text.isNotEmpty()) {
                push(ActCons.SearchGoodsActivity, {
                    it.withString("keyword", etSearch.text.toString())
                    it.withString("hint", etSearch.text.toString())
                })
                notifyShopView("")
                mViewModel.addHistory(HistoryBean(true, etSearch.text.toString()))
                return@setOnEditorActionListener true
            }
            return@setOnEditorActionListener false
        }
        //清除历史记录
        bt_search_clear.setOnClickListener {
            if (historyDatas.size > 0) {
                CancelSureViewModel(mActivity, R.string.确定清空历史搜索吗) {
                    mViewModel.clearHistory()
                }.show()
            }

        }
        //点击店铺
        llShop.setOnClickListener {
            if (etSearch.text.isNotEmpty()) {
                push(ActCons.SearchShopActivity, {
                    it.withString("keyword", etSearch.text.toString())
                })
                notifyShopView("")
                mViewModel.addHistory(HistoryBean(false, etSearch.text.toString()))
                pop()
            }
        }
        hotAdapter.setOnItemClickListener { adapter, view, position ->
            val hotModel = hotAdapter.getItem(position) as HotModel
            push(ActCons.SearchGoodsActivity, {
                it.withString("keyword", hotModel.hot_name)
                it.withString("hint", hotModel.hot_name)
            })
            mViewModel.addHistory(HistoryBean(true, hotModel.hot_name))
            pop()
        }
        historyAdapter.setOnItemChildClickListener { adapter, view, position ->
            val historyModel = historyAdapter.getItem(position) as HistoryBean
            when (view.id) {
                R.id.ll_search_history_gen -> {//点击ITEM
                    if (historyModel.searchMode) {
                        push(ActCons.SearchGoodsActivity, {
                            it.withString("keyword", historyModel.text)
                            it.withString("hint", historyModel.text)
                        })
                    } else {
                        push(ActCons.SearchShopActivity, {
                            it.withString("keyword", historyModel.text)
                        })
                    }
                    mViewModel.addHistory(historyModel)
                    pop()
                }
                R.id.iv_search_delete -> {//删除
                    mViewModel.deleteHistory(historyModel)
                }
            }
        }
        serviceKeyAdapter.setOnItemClickListener { adapter, view, position ->
            val keywordModel = serviceKeyAdapter.getItem(position) as KeywordModel
            push(ActCons.SearchGoodsActivity, {
                it.withString("keyword", keywordModel.words)
                it.withString("hint", keywordModel.words)
            })
            pop()
        }
        //防止穿透到下面
        ll_searchkey_servicekey.setOnClickListener {

        }
        etSearch.textChanges()
                .debounce(600, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    getSearchKeyword(etSearch.text.toString().trim())
                }
    }

  override fun startObserver()
    {
        mViewModel.loadHotDatasLiveData.observe(this, Observer {
            loadHotDatasResult(it)
        })
        mViewModel.loadHistoryDatasLiveData.observe(this, Observer {
            loadHistoryDatasResult(it)
        })
        mViewModel.getSearchKeywordLiveData.observe(this, Observer {
            getSearchKeywordResult(it[0] as ArrayList<KeywordModel>, it[1] as String)
        })
    }

    fun getSearchKeyword(keyword: String) {
        mViewModel.getSearchKeyword(keyword)

    }

    override fun initData() {

    }

    fun loadHotDatasResult(result: ArrayList<HotModel>?) {
        hotDatas.clear()
        if (!result.isNullOrEmpty()) {
            hotDatas.addAll(result!!)
        }
        notifyHotView()
    }

    fun loadHistoryDatasResult(result: ArrayList<HistoryBean>) {
        historyDatas.clear()
        if (!result.isNullOrEmpty()) {
            historyDatas.addAll(result!!)
        }
        notifyHistoryView()
    }

    fun getSearchKeywordResult(keywordModelList: ArrayList<KeywordModel>, keyword: String) {
        if (TextUtils.equals(etSearch.text.toString().trim(), keyword)) {
            serviceKeyDatas.clear()
            serviceKeyDatas.addAll(keywordModelList)
            serviceKeyAdapter.notifyDataSetChanged()
        }
    }
}